package top.kaoshanji.p1ch02a;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 代码清单 p1ch02a-01：使用反射API设置对象的属性值的示例(2.2节)
 * author kaoshanji
 * ^_^
 * create time 2024/12/23 11:31
 */
public class ReflectSetter {

    private static final Logger logger = LogManager.getLogger(ReflectSetter.class);

    public static void main(String[] args) {

        MyObject obj = new MyObject();

        try {
            ReflectSetter.invokeSetter(obj, "name", "Alex");
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            logger.error(e.getMessage());
        }

        System.out.println(obj.getName());

    }

    public static void invokeSetter(Object obj, String field, Object value) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        logger.info("...代码清单 p1ch02a-01：使用反射API设置对象的属性值的示例(2.2节)...");

        String methodName = "set" + field.substring(0, 1).toUpperCase() + field.substring(1);
        logger.debug("...methodName:{}...", methodName);

        Class<?> clazz = obj.getClass();
        Method method = clazz.getMethod(methodName, value.getClass());
        method.invoke(obj, value);
    }

    private static class MyObject {

        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }



}
